package com.zzy.chapter4.strategy;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.zzy.chapter4.pojo.Order;
import com.zzy.chapter4.utils.Constants;

import java.util.HashMap;

public class AlipayStrategy implements PayStrategyInterface {

    private AlipayClient alipayClient;

    public AlipayStrategy() {
        this.alipayClient = new DefaultAlipayClient(Constants.ALIPAY_GATEWAY_URL,
                Constants.APP_ID,
                Constants.APP_PRIVATE_KEY,
                "json", "UTF-8",
                Constants.ALIPAY_PUBLIC_KEY,
                Constants.SIGN_TYPE);
    }

    @Override
    public String pay(Order order) {
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setReturnUrl(Constants.CALLBACK_URL);
        HashMap<String, String> map = new HashMap<>();
        map.put("out_trade_no", order.getOrderId());
        map.put("total_amount", String.valueOf(order.getPrice()));
        map.put("subject", "商品");
        map.put("product_code", "FAST_INSTANT_TRADE_PAY");
        map.put("body", "商品详情");
        request.setBizContent(JSONUtil.toJsonStr(map));
        try {
            AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
            return response.getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
